package com.example.uploadresultliga.callapi;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;

import com.example.uploadresultliga.to.ResultadoEncuentro;
import com.example.uploadresultliga.util.ServicesParams;

public class CallUpdaterResultAPI extends AsyncTask<String, String, String> {

	@Override
    protected String doInBackground(String... params) {
		ResultadoEncuentro resultadoEncuentro = null;
    	StringBuilder resultToDisplay = new StringBuilder();
        try {
        	byte[] buffer = new byte[1024];
	        InputStream in = null;
            URL url = new URL(ServicesParams.RESULTADO_UPDATER+"?json_param="+params[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
            int i = in.read(buffer, 0, buffer.length);
            while(i!=-1) {
            	resultToDisplay.append(new String(buffer, "UTF-8"));
            	i = in.read(buffer, 0, i);
            }
            in.close();

            /*
            JSONObject jsonResEncObject=new JSONObject(resultToDisplay.toString().trim());
            resultadoEncuentro=new ResultadoEncuentro(convertToInt(jsonResEncObject.getString("id_club_local")), jsonResEncObject.getString("club_local"), convertToInt(jsonResEncObject.getString("ptos_local")), convertToInt(jsonResEncObject.getString("id_result_categ")), jsonResEncObject.getString("club_visit"), convertToInt(jsonResEncObject.getString("ptos_visit")));

            JSONArray jsonResCategoriasArray = jsonResEncObject.getJSONArray("result_categorias");
            for(int ii=0; ii<jsonResCategoriasArray.length(); ii++) {
            	JSONObject jsonResCategoria = jsonResCategoriasArray.getJSONObject(ii);
            	ResultadoCategoria rs = new ResultadoCategoria(convertToInt(jsonResCategoria.getString("id_res_cat")), convertToInt(jsonResCategoria.getString("id_cat")), convertToInt(jsonResCategoria.getString("cat")), convertToInt(jsonResCategoria.getString("goles_loc")), convertToInt(jsonResCategoria.getString("goles_visit")));
            	resultadoEncuentro.getResultadosCategorias().add(rs);
            }
            */
         } catch (Exception e) {
        	 e.printStackTrace();
         }
        return resultToDisplay.toString();
    }

	private Integer convertToInt(String s) {
		if(s == null || s.equalsIgnoreCase("null")) {
			return null;
		} else {
			return Integer.valueOf(s);
		}
	}

} // end